package stack;

import java.util.Stack;

public class leetcode32最长有效括号 {
    // 栈 时间O(n)，空间O(n)
    public int longestValidParentheses1(String s) {
        if (s == null) {
            return 0;
        }
        int length = s.length();
        int max = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    max = Integer.max(max, i - stack.peek());
                }
            }
        }
        return max;
    }
    // 时间O(n) 空间O(1)
    public int longestValidParentheses(String s) {
        if (s == null) {
            return 0;
        }
        int length = s.length();
        int left = 0;
        int right = 0;
        int max = 0;
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == '(') {
                left++;
            }
            if (s.charAt(i) == ')') {
                right++;
            }
            if (left == right) {
                max = Integer.max(max, left + right);
            }
            if (right > left) {
                left = 0;
                right = 0;
            }
        }
        left = 0;
        right = 0;
        for (int i = length - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') {
                left++;
            }
            if (s.charAt(i) == ')') {
                right++;
            }
            if (left == right) {
                max = Integer.max(max, left + right);
            }
            if (right < left) {
                left = 0;
                right = 0;
            }
        }
        return max;
    }
}
